package com.bluetooth.heartchecked;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class ThirdActivity extends AppCompatActivity {
    Button mBtnopenBt;
    Button mBtnsearchBt;
    BluetoothAdapter mBluetoothAdapter;

    public static void start(Context context) {
        Intent starter = new Intent(context, ThirdActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_third);
        //获取本地蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //判断蓝牙功能是否存在
        if (mBluetoothAdapter == null) {
            showToast("该设备不支持蓝牙...");
            return;
        }

        mBtnopenBt = this.findViewById(R.id.btn_open);
        mBtnopenBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭--打开蓝牙设备
                //判断蓝牙是否已经打开
                if(mBluetoothAdapter.isEnabled())
                {
                    showToast("蓝牙处于打开状态...");

                }else
                {
                    //打开蓝牙
                    boolean isOpen = mBluetoothAdapter.enable();
                    showToast("蓝牙的状态"+isOpen);
                }
            }
        });
       mBtnsearchBt = this.findViewById(R.id.btn_search);
       mBtnsearchBt.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               if(mBluetoothAdapter.startDiscovery())
               {
                   showToast("开始搜索...");
               }else
               {
                   boolean isOpen = mBluetoothAdapter.startDiscovery();
                   showToast("蓝牙的状态"+isOpen);
               }
           }
       });


    }

    public void showToast(String msg) {
        Toast toast = Toast.makeText(this, msg, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER_HORIZONTAL,0,0);
        toast.show();
    }
}
